<template>
	<div class="login">
		<div class="login-info" @click="handleLogin">
			<img class="img-c" src="../../assets/images/wx.png" alt="" />
			<div class="text">授权登录</div>
		</div>
	</div>
</template>
<script setup lang="ts">
	import { useRouter } from "vue-router";
	import { getCookie, setCookie } from "@/utils";
	import { login } from "@/api/home";
	import { showToast } from "vant";
	import { json } from "stream/consumers";
	const router = useRouter();
	const params = new URLSearchParams(location.search);
	let redirect = params.get("redirect");
	console.log('redirectredirectredirect',redirect)
	if (getCookie("token")) { // 之前已经登录绑定过
		if (redirect) {
			router.push(redirect);
		} else {
			router.push("/businesspush");
		}
	} else { // 从未登录绑定过
		let code = "";
		let pid = localStorage.getItem('pid') ? localStorage.getItem('pid') : "";
		code = params.get("code") || "";
		
		if (pid) {
			pid = JSON.parse(pid);
		}
		if (code) {
			setCookie({
				key: "code",
				value: code,
				expireDays: 1,
			});
			login({ code: code, pid: Number(pid) }).then((res) => {
				if (res.code == 300) {
					location.href = "https://wx.yewudaotech.com/supply.html";
				} else {
					if (res.data.id) {
						setCookie({
							key: "token",
							value: res.data.id,
							expireDays: 1,
						});
						localStorage.setItem("userInfo", JSON.stringify(res.data));
						if (redirect) {
							router.push(redirect);
						} else {
							router.push("/businesspush");
						}
					} else {
						showToast("登录失败");
					}
				}
			});
		} else {
			const param = "?pid=" + pid;
			const hrefUrl = encodeURI(window.location.href +param);
			console.log('这是hrefUrl：', hrefUrl)
			window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf64aa6106b875289&redirect_uri=${encodeURIComponent(
				hrefUrl
			)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;


		}
	}
	const handleLogin = () => {
		location.reload();
	};
</script>
<style lang="scss" scoped>
	.login {
		min-height: 100vh;
		background-color: #fff;

		.login-info {
			padding-top: 30vh;
			display: flex;
			justify-content: center;
			flex-direction: column;
			align-items: center;

			.img-c {
				width: 80px;
				height: 80px;
			}

			.text {
				margin-top: 10px;
			}
		}
	}
</style>